//
//  EncodeToMP4.m
//  EncodeVideo
//
//  Created by 刘泽琛 on 14-3-22.
//  Copyright (c) 2014年 刘 泽琛. All rights reserved.
//

#import "EncodeToMP4.h"

@implementation EncodeToMP4 {
    OpenVC openVC;
}

- (id)init {
    if (self = [super init]) {
        //
    }
    return self;
}


//开始摄像

- (id)initWithPickVideo:(OpenVC)block {
    if (self = [super init]) {
        UIImagePickerController *pickerView = [[UIImagePickerController alloc] init];
        pickerView.sourceType = UIImagePickerControllerSourceTypeCamera;
        NSArray* availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        pickerView.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
        pickerView.videoMaximumDuration = 30;
        pickerView.delegate = self;
        
        openVC = block;
        openVC(pickerView);
    }
    return self;
}



#pragma mark 系统Camera委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    videoURL = info[UIImagePickerControllerMediaURL];
    // 文件大小[self getFileSize:[[_videoURL absoluteString] substringFromIndex:16]]];
    // [self getVideoDuration:_videoURL]];
    _hasVideo = YES;
    [picker dismissViewControllerAnimated:YES completion:nil];
    // [self start];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    _hasVideo = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
    // [self start];
}

- (void)start:(NSURL *)url hasVideo:(BOOL)hasVideo isSave:(BOOL)isSave
 {
    if (!hasVideo)
    {
        return;
    }
     self.isSave = isSave;
     AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
     NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
     // 高质量 AVAssetExportPresetHighestQuality|AVAssetExportPresetMediumQuality|AVAssetExportPresetLowQuality
     
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])
        
    {
        UIActivityIndicatorView* activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        activity.frame = CGRectMake(100,20,CGRectGetWidth(alert.frame),CGRectGetHeight(alert.frame));
        [alert addSubview:activity];
        [activity startAnimating];
        [alert show];
        startDate = [NSDate date];
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                         presetName:AVAssetExportPresetMediumQuality];
        NSDateFormatter* formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
         if (![fileManager fileExistsAtPath:YinHang_Local_Video]) {
         [fileManager createDirectoryAtPath:YinHang_Local_Video withIntermediateDirectories:YES attributes:nil error:nil];
         }
        mp4Path = [YinHang_Local_Video stringByAppendingFormat:@"/compress.mp4"];
        NSError *error;
        if ([fileManager fileExistsAtPath:mp4Path]) {
            [fileManager removeItemAtPath:mp4Path error:&error];
        }
        // modify by lzc
        exportSession.outputURL = [NSURL fileURLWithPath:mp4Path];
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                {
                    [alert dismissWithClickedButtonIndex:0 animated:NO];
                    UIAlertView* alert_ = [[UIAlertView alloc] initWithTitle:@"警告" message:[[exportSession error] localizedDescription] delegate:nil cancelButtonTitle:@"好" otherButtonTitles: nil];
                    [alert_ show];
                    break;
                }
                    
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"视频输出失败！");
                    [alert dismissWithClickedButtonIndex:0
                                                animated:YES];
                    break;
                case AVAssetExportSessionStatusCompleted:
                    NSLog(@"视频输出成功！");
                    [self performSelectorOnMainThread:@selector(convertFinish) withObject:nil waitUntilDone:NO];
                    break;
                default:
                    break;
            }
        }];
    } else {
        UIAlertView *alert_ = [[UIAlertView alloc] initWithTitle:@"警告" message:@"AVAsset doesn't support mp4 quality" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert_ show];
    }
}

#pragma mark 转换完成

- (void)convertFinish {
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    NSLog(@"视频转码后大小:%ldK",(long)[self getFileSize:mp4Path]);
    hasMp4 = YES;
    [self save];
}

- (void)save {
    if (!hasMp4)
    {
        return;
    }
    NSString *encodeFinishedPath = [NSString stringWithFormat:@"file://localhost/private%@", mp4Path];
    self.resultUrl = [NSURL URLWithString:encodeFinishedPath];
    
    if (self.isSave) {
        [self toSaveVideo:self.resultUrl];
    }else {
        [_delegate backResultDatainfo:self.resultUrl];
    }
    /*// 所需要上传的视频文件（压缩后的）
    self.resultData = [NSData dataWithContentsOfURL:self.resultUrl];
    [_delegate backResultDatainfo:self.resultUrl];*/
}

- (void)toSaveVideo:(NSURL *)url {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
        [assetLibrary writeVideoAtPathToSavedPhotosAlbum:url
                                         completionBlock:
         ^(NSURL *assetURL, NSError *error) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSString *title;
                 NSString *message;
                 
                 if (error != nil) {
                     title = @"保存视频失败";
                     message = [error localizedDescription];
                 }
                 else {
                     title = @"保存视频成功";
                     message = nil;
                 }
                 // 视频保存到本地以后
                 [_delegate backResultDatainfo:url];
             });
         }];
    });
}

#pragma mark 获取文件大小

- (NSInteger) getFileSize:(NSString*) path
{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path]) {
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue]/1024;
        else
            return - 1;
    }
    else
    {
        return - 1;
    }
}

@end
